#include "DataProvider.h"

DataProvider::DataProvider(DataBaseAgent* database, QObject* parent) :
	QObject(parent),
	_database(database),
	_crypt(new CryptoAgent()),
	_statusBar(NULL),
	_databaseLoaded(false)
{
}

QList<Note*> DataProvider::getNotesList()
{
	return _notes;
}

DataBaseAgent* DataProvider::getDatabase()
{
	return _database;
}

CryptoAgent* DataProvider::getCrypt()
{
	return _crypt;
}

bool DataProvider::addNote(Note* note)
{
	int res = _database->addNote(*note);
	if(res == -1){
		return false;
	}
	note->setId(res);

	_notes.append(note);
	emit noteAdded(note);
	return true;
}

bool DataProvider::removeNote(Note* note)
{
	for(int i=0;i<_notes.size();i++){
		if(_notes.at(i) == note){
			if(_database->removeNote(*note)){
				_notes.removeAt(i);
				emit noteRemoved(note);
				return true;
			}
		}
	}
	return false;
}

bool DataProvider::updateNote(Note* note)
{
	if(_database->updateNote(*note)){
		emit noteUpdated(note);
		return true;
	}
	return false;
}

void DataProvider::loadDatabase()
{
	if(!_database) return;

	foreach(Note* note, _notes){
		emit noteRemoved(note);
	}

	_databaseLoaded = true;
	emit DBStateChanged();

	/// TODO: delete notes from memory

	_notes = _database->getNotesList();

	foreach(Note* note, _notes){
		emit noteAdded(note);
	}
}

void DataProvider::setStatusBar(QStatusBar* statusBar)
{
	_statusBar = statusBar;
}

void DataProvider::showMessage(QString msg, int timeout)
{
	if(_statusBar == NULL) return;

	_statusBar->showMessage(msg, timeout);
}
